﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyCommerce.ManagementBase.Common.Base.Common;
using MyCommerce.Presentation.UsersAndSecurity.Presenters;
using MyCommerce.Presentation.UsersAndSecurity.IViews;
using Innova.FoundationFramework.DataTypes;
using Innova.Microfinanzas.BusinessEntities;
using Innova.Microfinanzas.BusinessEntities.SystemEnums;

namespace MyCommerce.Windows.UsersAndSecurity.Views
{
    public partial class UserFillView : BaseForm, IUserFillView
    {
        private UserFillPresenter pPresenter;

        public UserFillView()
        {
            InitializeComponent();
            pPresenter = new UserFillPresenter(this);
        }

        #region IUserFillView Members

        public long IdItemEdit { get; set; }

        public OptionSelect OptionViewSelect { get; set; }

        public List<Role> ColRolesLoad 
        {
            set
            {
                listRoles.DisplayMember = "RoleName";
                listRoles.ValueMember = "IdRole";
                listRoles.DataSource = value;
            }
        }
        
        public List<Employee> ColEmployeesLoad 
        {
            set
            {
                listEmployees.DisplayMember = "FullName";
                listEmployees.ValueMember = "IdEmployee";
                listEmployees.DataSource = value;
            }
        }

        public User Get()
        {
            return User.CreateUser(0, fieldUserName.Text.Trim(), fieldPassword.Text.Trim(), fieldIsActive.Checked, Convert.ToInt64(listEmployees.SelectedValue), Convert.ToInt64(listRoles.SelectedValue), false);
        }

        public void Set(User objUserToLoad)
        {
            IdItemEdit = objUserToLoad.IdUser;
            fieldUserName.Text = objUserToLoad.UserName;
            fieldPassword.Text = objUserToLoad.Password;
            fieldIsActive.Checked = objUserToLoad.IsActive;
            if (String.IsNullOrEmpty(listRoles.ValueMember) == false)
                listRoles.SelectedValue = objUserToLoad.IdRole;
            if (String.IsNullOrEmpty(listEmployees.ValueMember) == false)
                listEmployees.SelectedValue = objUserToLoad.IdEmployee;
        }

        public void CloseAndSetResult(bool result)
        {
            if (result)
                Context.ShowInformationMessageBox("La información se guardó correctamente.", "Creación/Edición de usuarios.");
            Result = result;
            Close();
        }

        public event GenericEventHandler<User> OnLoadView;

        public event EventHandler OnSave;

        public event EventHandler OnCancel;

        #endregion

        private void UserFillView_Load(object sender, EventArgs e)
        {
            User objUser = null;
            OptionViewSelect = OptionSelect.Create;
            if (Parameter != null)
            {
                objUser = (User)Parameter;
                labelContainer3.Visible = false;
                labelContainer4.Visible = false;
                OptionViewSelect = OptionSelect.Edit;                
            }
            if (OnLoadView != null)
                OnLoadView(this, new GenericEventArgs<User>(objUser));
            fieldPassword.CharacterCasing = CharacterCasing.Normal;
            fieldPasswordConfirm.CharacterCasing = CharacterCasing.Normal;
        }

        private void tsCancelButtonToolStrip_Click(object sender, EventArgs e)
        {
            if (OnCancel != null)
                OnCancel(this, new EventArgs());
        }

        private void tsSaveButtonToolStrip_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateView())
                {
                    if (OnSave != null)
                        OnSave(this, new EventArgs());
                }
            }
            catch (Exception ex)
            {
                Context.HandleException(ex);
            }
        }

        private bool ValidateView()
        {
            bool vResult = true;
            StringBuilder message = new StringBuilder();

            if (string.IsNullOrEmpty(fieldUserName.Text.Trim()))
            {
                vResult = false;
                message.AppendLine("Debe ingresar un nombre de usuario.");
            }

            if (listEmployees.SelectedIndex == -1)
            {
                vResult = false;
                message.AppendLine("Debe elegir un empleado asociado al usuario.");
            }

            if (listRoles.SelectedIndex == -1)
            {
                vResult = false;
                message.AppendLine("Debe elegir un rol asociado al usuario.");
            }

            if (labelContainer3.Visible)
            {
                bool isPasswordFill = true;

                if (string.IsNullOrEmpty(fieldPassword.Text.Trim()))                
                {
                    isPasswordFill = false;
                    vResult = false;
                    message.AppendLine("Debe ingresar una contraseña.");
                }

                if (string.IsNullOrEmpty(fieldPasswordConfirm.Text.Trim()))
                {
                    isPasswordFill = false;
                    vResult = false;
                    message.AppendLine("Debe ingresar la confirmación de la contraseña.");
                }

                if (isPasswordFill)
                {
                    if (fieldPassword.Text.Trim() != fieldPasswordConfirm.Text.Trim())
                    {
                        vResult = false;
                        message.AppendLine("Las contraseñas ingresadas son diferentes, por favor vuelva a ingresar ambas.");
                    }
                }
            }

            if (!vResult)
            {
                Context.ShowErrorMessageBox(message.ToString(), "Validación de datos.");
            }

            return vResult;
        }
    }
}
